package com.simdo.g768.Util;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;

import com.g768.Bean.UeidBean;
import com.simdo.g768.Bean.MyUeidBean;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;

public class ExcelUtil {

    public interface OnReadProgressListener {
        void onReadProgress(int position);
        void onReadOk(HashSet<MyUeidBean> set, int allCount, int okCount, int errCount, int reCount);
        void onReadFail(String err);
    }

    public static class ExcelReaderTask extends AsyncTask<Void, Void, Void> {
        private final InputStream inputStream;
        private final OnReadProgressListener listener;
        HashSet<MyUeidBean> set = null;// 用来存放表中数据
        private int allCount, errCount;

        public ExcelReaderTask(InputStream inputStream, OnReadProgressListener listener) {
            this.inputStream = inputStream;
            this.listener = listener;
            allCount = 0;
            errCount = 0;
        }

        @Override
        protected Void doInBackground(Void... params) {
            Workbook workbook;
            try {
                workbook = WorkbookFactory.create(inputStream);
                Sheet sheet = workbook.getSheetAt(0);
                // 获取最大行数
                allCount = sheet.getPhysicalNumberOfRows();
                //获取最大列数  默认使用第一行来判断
                Row row = sheet.getRow(0);
                int cell = row.getPhysicalNumberOfCells();
                set = new HashSet<>();
                for (int i = 0; i < allCount; i++) {
                    boolean isOk = true;
                    MyUeidBean bean = new MyUeidBean();
                    row = sheet.getRow(i);
                    if (row != null) {
                        for (int j = 0; j < cell; j++) {
                            String iStr = getCellFormatValue(row.getCell(j)).toString();
                            iStr = iStr.replaceAll(" ", "");
                            iStr = iStr.replaceAll("\t", "");
                            iStr = iStr.replaceAll("\n", "");
                            if (iStr.isEmpty()) {
                                isOk = false;
                                errCount++;
                                break;
                            }
                            if (j == 0) bean.setName(iStr);
                            else if (j == 1) bean.setmUeidBean(new UeidBean(iStr, ""));
                        }
                    } else {
                        break;
                    }
                    if (isOk) set.add(bean);
                    listener.onReadProgress(i * 100 / allCount);
                }
            } catch (Exception e) {
                AppLog.D("readExcel e = " + e);
                listener.onReadFail(e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // 读取完毕后的操作
            listener.onReadOk(set, allCount, set.size(), errCount, allCount - errCount - set.size());
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    /**
     * 读取excel   （xls和xlsx）
     * @return
     */
    public static void readExcel(String fileFullPath, OnReadProgressListener listener) {
        File file = new File(fileFullPath);
        String filePath = file.getAbsolutePath();
        InputStream is;
        try {
            is = new FileInputStream(filePath);
            new ExcelReaderTask(is, listener).execute();
        } catch (Exception e) {
            AppLog.D("readExcel e = " + e);
            listener.onReadFail(e.getMessage());
        }
    }

    public static void readExcel(Context context, Uri uri, OnReadProgressListener listener) {
        InputStream is;
        try {
            is = context.getContentResolver().openInputStream(uri);
            new ExcelReaderTask(is, listener).execute();
        } catch (Exception e) {
            AppLog.D("readExcel e = " + e);
            listener.onReadFail(e.getMessage());
        }
    }


    /**	获取单个单元格数据
     * @param cell
     * @return
     * @author lizixiang ,2018-05-08
     */
    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;

        if (cell != null) {
            // 判断cell类型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: {
                    java.text.DecimalFormat formatter = new java.text.DecimalFormat("########");
                    cellValue = formatter.format(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA: {
                    // 转换为日期格式YYYY-mm-dd
                    cellValue = cell.getDateCellValue();
                    break;
                }
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
}
